package com.digitalchina.lxnsy.activity.management;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.WebViewActivity;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.BusinessAnalysisVO;
import com.digitalchina.lxnsy.entity.SeedVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.xml.AdminXML;
import com.digitalchina.lxnsy.xml.UserXML;
import com.lzy.okhttputils.model.HttpParams;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity.management
 * 创建人：郑皓
 * 创建时间：2019/4/26 11:17
 * 修改备注：
 * ================================================
 */
public class BusinessSituationActivity extends BaseActivity {

    @Bind(R.id.tv_start_date)
    TextView tvStartDate;
    @Bind(R.id.tv_end_date)
    TextView tvEndDate;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_area)
    TextView tvArea;
    @Bind(R.id.tv_order)
    TextView tvOrder;
    @Bind(R.id.tv_order_finish)
    TextView tvOrderFinish;
    @Bind(R.id.tv_income)
    TextView tvIncome;
    @Bind(R.id.tv_expend)
    TextView tvExpend;
    @Bind(R.id.tv_profit)
    TextView tvProfit;
    @Bind(R.id.tv_seed_dosage)
    TextView tvSeedDosage;
    @Bind(R.id.tv_fertilizer_dosage)
    TextView tvFertilizerDosage;
    @Bind(R.id.tv_pesticide_ml)
    TextView tvPesticideMl;
    @Bind(R.id.tv_pesticide_g)
    TextView tvPesticideG;
    @Bind(R.id.layout_result)
    LinearLayout layoutResult;

    private OptionsPickerView pvName;
    private DatePickerDialog pvDateStart, pvDateEnd;

    private String cropId = "";// 农作物ID


    private int mYear;
    private int mMonth;
    private int mDayOfMonth;

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_business_situation);
        setTitle("经营情况");
    }

    @Override
    public void initMember() {

        getSeedList();

        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        pvDateStart = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                tvStartDate.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
            }
        }, mYear, mMonth, mDayOfMonth);

        pvDateEnd = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                tvEndDate.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
            }
        }, mYear, mMonth, mDayOfMonth);

    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case MSG_S_0: // 查询
                        setView(message.obj.toString());
                        break;
                    case MSG_F_0:
                        showToast(message.obj.toString());
                        break;
                    case MSG_S_1:
                        callBack(message.obj);
                        break;
                }
                return false;
            }
        });
    }

    private void setView(String json) {
        BusinessAnalysisVO vo = FastJsonUtil.getBean(json, "businessAnalysis", BusinessAnalysisVO.class);

        if(vo!=null){
            tvArea.setText(vo.getLandArea());
            tvOrder.setText(vo.getAllocationOrders());
            tvOrderFinish.setText(vo.getCompleteOrderQuantity());
            tvIncome.setText(vo.getTotalIncome());
            tvExpend.setText(vo.getTotalPay());
            tvProfit.setText(vo.getTotalProfit());
            tvSeedDosage.setText(vo.getTotalFeedDosage());
            tvFertilizerDosage.setText(vo.getTotalFertilizerDosage());
            tvPesticideMl.setText(vo.getTotalPesticideDosageml());
            tvPesticideG.setText(vo.getTotalPesticideDosageg());
        }

        layoutResult.setVisibility(View.VISIBLE);

    }

    @Override
    public void callBack(Object object) {

        final List<SeedVO> voList = FastJsonUtil.getListBean(object.toString(), "list", SeedVO.class);

        // 设置分类
        pvName = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {

                if (voList == null || voList.size() == 0){
                    showToast("正在获取作物，请稍候重试");
                    return;
                }
                tvName.setText(voList.get(options1).getPickerViewText());
                cropId = voList.get(options1).getId();

            }
        })
                .setTitleText("作物")
                .setSubCalSize(16)//确定取消按钮大小
                .setLineSpacingMultiplier(1.5f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
                .setDividerColor(getResources().getColor(R.color.colorFontLightGrayB))//设置分割线的颜色
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(18)//设置滚轮文字大小
                .setSelectOptions(0)  //设置默认选中项
                .build();
        pvName.setPicker(voList);

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.layout_start_date, R.id.layout_end_date, R.id.layout_name, R.id.bt_query, R.id.bt_history})
    public void onViewClicked(View view) {
        hideKeyboard();
        switch (view.getId()) {
            case R.id.layout_start_date:
                pvDateStart.show();
                break;
            case R.id.layout_end_date:
                pvDateEnd.show();
                break;
            case R.id.layout_name:
                if (pvName != null)
                    pvName.show();
                else {
                    showToast("正在获取作物");
                }
                break;
            case R.id.bt_query:
                query();
                break;
            case R.id.bt_history:
                Map<String, String> map = new HashMap<>();
                map.put("title", "查询历史");
                map.put("url", getUrl());
                GotoUtil.gotoActivity(activity, WebViewActivity.class, "map", map);
                break;
        }
    }

    private String getUrl() {
        String url = URL.URL_BUSINESS_ANALYSIS_H5 +
                "?enterpriseId=" + AdminXML.getEnterpriseId(activity)+
                "&resNo=" + AdminXML.getResNo(activity)+
                "&LOGIN=" + UserXML.getLOGIN(activity)+
                "&userAccId=" + AdminXML.getUserAccId(activity);
        return url;
    }

    private void query() {

        if (StringUtil.isTextEmpty(tvStartDate)) {
            showToast("请选择开始日期");
            return;
        }
        if (StringUtil.isTextEmpty(tvEndDate)) {
            showToast("请选择开始日期");
            return;
        }
        if (StringUtil.isTextEmpty(tvName)) {
            showToast("请选择农作物");
            return;
        }

        /**
         * startTime	开始日期
         * endTime	结束日期
         * cropId	农作物ID
         */

        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));
        params.put("userAccId", AdminXML.getUserAccId(activity));
        params.put("startTime", tvStartDate.getText().toString());
        params.put("endTime", tvEndDate.getText().toString());
        params.put("cropId", cropId);

        OkHttpUtil.post(activity, URL.URL_BUSINESS_ANALYSIS, "正在查询", params, mHandler,
                MSG_S_0, MSG_F_0);
    }

    // 获取农作物品种 0不带品种  1带品种
    private void getSeedList() {
        HttpParams params = new HttpParams();
        params.put("enterpriseId", AdminXML.getEnterpriseId(activity));
        params.put("resNo", AdminXML.getResNo(activity));
        params.put("type", "0");

        OkHttpUtil.post(activity, URL.URL_GET_SEED_LIST, "", params, mHandler,
                MSG_S_1, MSG_F_1);
    }


}
